<?php
namespace app\staff\controller;
use addons\message\model\NewsMessage;
use app\admin\model\publicuse\HerTime;
use app\api\model\CommentUser;
use app\api\model\Notice;
use app\api\model\NursingOrder;
use app\BaseController;
use app\staff\model\EmployeeInformation;
use app\staff\model\OrderCheck;
use app\staff\model\ServiceContent;
use app\staff\model\StaffGrade;
use app\staff\model\StaffPeople;
use app\staff\model\StaffSkill;
use app\staff\model\StudyCourse;
use app\staff\model\UserSkill;
use think\Request;

class Staffhand extends BaseController
{
    /**获取员工未读消息条数
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_message_count(Request $request){
        $count = NewsMessage::getStaffCount($request->user['id']);
        return api_success('获取成功',$count);
    }

    /**获取员工端消息列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_message_list(Request $request){
        $user = $request->user;
        $limit = $request->param('limit',10);
        $res = NewsMessage::getStaffMessageList($user['id'],$limit);
        return api_success('获取成功',$res);
    }

    /**获取消息详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_message_info(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            return api_fail('请输入id');
        }
        $data = NewsMessage::where('id',$id)
            ->find();
        if(empty($data)){
            return api_fail('消息不存在');
        }
        $data->read = 1;
        $data->save(['update_time'=>time()]);
        return api_success('获取成功',$data->toArray());
    }

    /**获取公告列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function get_notice_list(Request $request){
        $user = $request->user;
//        $up_getmessage_time = Users::where('id',$user['id'])
//            ->value('up_getmessage_time');
        $limit = $request->param('limit',10);
        $data = Notice::where('status',1)
            ->where('type','in',[0,2])
            ->withoutField('sort,delete_time,type')
            ->paginate($limit)
            ->toArray();
        $page = $request->param('page');
        if($page==1){
            StaffPeople::where('id',$user['id'])->save(['up_getmessage_time'=>time()]);
        }
        return api_success('获取成功',$data['data']);
    }

    /**获取公告详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_notice_info(Request $request){
        $id = $request->param('id');
        $data = Notice::where('id',$id)
            ->withoutField('sort,delete_time,type')
            ->findOrEmpty()->toArray();
        return api_success('获取成功',$data);
    }

    /**获取用户详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_user_info(Request $request){
        $user = $request->user;
//        echo '<pre>';
//        print_r($user);
//        exit;
        $employee_information = EmployeeInformation::where('staff_people_id',$user['id'])
//            ->withoutField('id,delete_time,sort,name,create_time,update_time,status')
            ->field('city,city_code,heights,weights,constellation,introduce,experience,certificates,service_num,service_time,(YEAR(CURDATE())-YEAR(birth_data)) as age,(YEAR(CURDATE())-YEAR(entry_time)) as entry')
            ->findOrEmpty()->toArray();
//        echo '<pre>';
//        print_r($employee_information);
//        exit;
        $user = array_merge($user,$employee_information);
        if($user['pid']==0){
            $user['pid'] = '';
        }else{
            $pid = StaffPeople::where('id',$user['pid'])
                ->value('name');
            $user['pid'] = $pid;
        }
        $res['user'] = $user;
        $curriculum = StudyCourse::where('status',1)
            ->where('pid',0)
            ->order('sort desc,id asc')
            ->field('id,name,type')
            ->select()->each(function ($item){
                $item->count = StudyCourse::where('status',1)
                    ->where('pid',$item->id)
                    ->count();
                return $item;
            })->toArray();
        $res['curriculum'] = $curriculum;
        return api_success('获取成功',$res);
    }

    /**获取我的订单
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function get_order_list(Request $request){
        $user = $request->user;
        $type = $request->param('type',0);
        $limit = $request->param('limit',10);
        $where = [
            ['status','=',1],
            ['state','<>',5],
            ['staff_people_id','=',$user['id']],
        ];
        if($type==1){
            $where[] = ['is_meet','=',0];
        }elseif ($type==2){
            $where[] = ['is_meet','=',1];
            $where[] = ['state','=',2];
        }elseif ($type==3){
            $where[] = ['state','in',[3,4]];
        }
        $data = NursingOrder::where($where)
            ->field('id,name,service_time,assessment_time,state,pay_state,is_meet,nursing_lang_id')
            ->with(['nursing_lang'=>function($sql){
                $sql->field('id,name,img');
            }])
            ->order('create_time desc')
            ->paginate($limit)
            ->each(function ($item)use ($type){
                if($type==0){
                    if($item->is_meet==0){
                        $item->type = 1;
                    }elseif ($item->is_meet==1&&$item->state==2){
                        $item->type = 2;
                    }elseif(in_array($item->state,[3,4])){
                        $item->type = 3;
                    }
                }else{
                    $item->type = $type;
                }
                return $item;
            })
            ->toArray();
        return api_success('获取成功',$data['data']);
    }

    /**获取订单详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_order_info(Request $request){
        $id = $request->param('id');
        $user = $request->user;
        $data = NursingOrder::where('id',$id)
            ->field('id,name,cover_pepo_name,cover_pepo_sex,is_live,phone,province,city,area,address,service_time,assessment_time,end_time,state,pay_state,is_meet,nursing_lang_id,staff_people_id,create_time,purchase_time,days,money')
            ->with(['nursing_lang'=>function($sql){
                $sql->field('id,name,img');
            }])->find();
        if(empty($data)){
            return api_fail('订单不存在');
        }
        if(intval($data->getData('staff_people_id'))!==intval($user['id'])){
            return api_fail('订单不属于你');
        }
        if($data->is_meet==0){
            $data->type = 1;
        }elseif ($data->is_meet==1&&$data->state==2){
            $data->type = 2;
        }elseif(in_array($data->state,[3,4])){
            $data->type = 3;
        }
        if($data->getData('state')==4){
            $comment = CommentUser::where('nursing_order_id',$data->id)
                ->field('id,create_time,content,imgs,uid')
                ->with(['getuser'=>function($sql){
                    $sql->field('id,name,head_img');
                }])
                ->findOrEmpty();
            $data->comment = $comment;
        }else{
            $data->comment = '';
        }
        return api_success('获取成功',$data->toArray());
    }

    /**确认接单
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function confirm_meet(Request $request){
        $id = $request->param('id');
        $user = $request->user;
        if(empty($id)){
            return api_fail('请输入要接的订单');
        }
        $order = NursingOrder::find($id);
        if(empty($order)){
            return api_fail('订单不存在');
        }
        if(intval($order->getData('staff_people_id'))!==intval($user['id'])){
            return api_fail('订单不属于你');
        }
        $order->is_meet = 1;
        $bool = $order->save(['update_time'=>time()]);
        if(!$bool){
            return api_fail('接单失败');
        }
        return api_success('接单成功');
    }

    /**获取订单服务内容
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_order_service(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            return api_fail('请添加要查询的订单');
        }
        $order = NursingOrder::find($id);
        if(empty($order)){
            return api_fail('订单不存在');
        }
        $data = ServiceContent::where('status',1)
            ->where('pid',0)
            ->where('nursing_lang_id',$order->getData('nursing_lang_id'))
            ->order('id asc')
            ->withoutField('sort,delete_time,pid,nursing_lang_id,update_time,status')
            ->select()->each(function ($item){
                $child = ServiceContent::where('status',1)
                    ->where('pid',$item->id)
                    ->withoutField('sort,delete_time,pid,nursing_lang_id,update_time,status')
                    ->order('sort desc')
                    ->select();
                $item->child = $child;
                return $item;
            })->toArray();
        return api_success('获取成功',$data);
    }

    /**签到成功
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add_check_in(Request $request){
        $data = $request->param();
        $user = $request->user;
        $array = [
            'id|签到的订单'=>'require',
            'data|签到的内容'=>'require',
        ];
        $this->validate($data,$array);
        $order = NursingOrder::find($data['id']);
        if(empty($order)){
            return api_fail('订单不存在');
        }
        if(intval($order->getData('staff_people_id'))!==intval($user['id'])){
            return api_fail('订单不属于你');
        }
//        $data['data'] = [
//            191,
//            192,
//            193,
//            194,
//            195,
//            196,
//            197,
//            198,
////            199,
//            200,
//            201,
//            202,
//            203,
//            204,
//            205,
//            206,
//            207,
//            208,
//            209,
//            210,
//            211,
//            213,
//            215,
//            216,
//            217,
//            219,
//            220,
//        ];
        $newdata = [];
        foreach ($data['data'] as $value){
            $service_content = ServiceContent::where('status',1)
                ->where('id',$value)
                ->field('id,name,pid')
                ->find();
            if($service_content->getData('pid')!=0){
                if(isset($newdata[$service_content->getData('pid')])){
                    $newdata[$service_content->getData('pid')]['child'][] = $service_content->toArray();
                }else{
                    $pidname = ServiceContent::where('id',$service_content->getData('pid'))
                        ->value('name');
                    $newdata[$service_content->getData('pid')]['name'] = $pidname;
                    $newdata[$service_content->getData('pid')]['child'][] = $service_content->toArray();
                }
            }
        }
        list($start,$end) = HerTime::today();
        $order_check = OrderCheck::where('status',1)
            ->where('nursing_order_id',$order->getData('id'))
            ->where('create_time','>',$start)
            ->where('create_time','<=>',$end)
            ->find();
        if(empty($order_check)){
            $order_check = [
                'nursing_order_id'=>$order->getData('id'),
                'content'=>json_encode($newdata,JSON_UNESCAPED_UNICODE),
                'status'=>1,
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            $bool = OrderCheck::create($order_check);
        }else{
            $order_check->content = json_encode($newdata,JSON_UNESCAPED_UNICODE);
            $bool = $order_check->save(['update_time'=>time()]);
        }
        if(!$bool){
            return api_fail('签到失败');
        }
        return api_success('签到成功');
    }

    /**获取今日是否签到
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_check_in(Request $request){
        $id = $request->param('id');
        $user = $request->user;
        if(empty($id)){
            return api_fail('请输入要查询的订单');
        }
        $date = $request->param('date');
        if(empty($date)){
            list($start,$end) = HerTime::today();
        }else{
            list($start,$end) = HerTime::today(strtotime($date));
        }
        $order = NursingOrder::find($id);
        if(intval($order->getData('staff_people_id'))!==intval($user['id'])){
            return api_fail('订单不属于你');
        }
        $count = OrderCheck::where('status',1)
            ->where('nursing_order_id',$id)
            ->where('create_time','>',$start)
            ->where('create_time','<=',$end)
            ->count();
        return api_success('获取成功',['count'=>$count]);
    }

    /**获取签到详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_check_info(Request $request){
        $id = $request->param('id');
        $user = $request->user;
        if(empty($id)){
            return api_fail('请输入要查询的订单');
        }
        $date = $request->param('date');
        if(empty($date)){
            list($start,$end) = HerTime::today();
        }else{
            list($start,$end) = HerTime::today(strtotime($date));
        }
        $order = NursingOrder::find($id);
        if(intval($order->getData('staff_people_id'))!==intval($user['id'])){
            return api_fail('订单不属于你');
        }
        $data = OrderCheck::where('status',1)
            ->where('nursing_order_id',$id)
            ->where('create_time','>',$start)
            ->where('create_time','<=',$end)
            ->withoutField('status,delete_time,nursing_order_id,update_time')
            ->findOrEmpty()->toArray();
        if(empty($data)){
            return api_fail('没有签到信息');
        }
        $data['create_time'] = date('Y-m-d H:i',strtotime($data['create_time']));
        return api_success('获取成功',$data);
    }

    /**获取已完成培训
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function complete(Request $request){
        $user = $request->user;
//        $user = StaffPeople::find($user['id']);
        //处理课程
        $curriculum = StudyCourse::where('status',1)
            ->where('pid','<>',0)
            ->order('pid asc,sort desc')
            ->field('id,name')
            ->withCount('kechen')
            ->select()->toArray();
        $has = 0;
        foreach ($curriculum as $value){
            if($value['kechen_count']>0){
                $has++;
            }
        }
        $res['curriculum'] = [
            'count'=>count($curriculum),
            'has'=>$has,
            'child'=>$curriculum,
        ];
        //处理技能
        $skill = UserSkill::where('uid',$user['id'])
            ->where('status',1)
            ->order('staff_skill_id asc')
            ->field('id,name')
            ->select()->toArray();
        $res['skill'] = [
            'count'=>count($skill),
            'child'=>$skill,
        ];
        //处理证书
        $employee_information = EmployeeInformation::where('staff_people_id',$user['id'])
            ->field('certificates')
            ->findOrEmpty()->toArray();
        $res['certificate'] = $employee_information['certificates']??[];
        return api_success('获取成功',$res);
    }

    /**获取下一阶段目标
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function next_target(Request $request){
        $user = StaffPeople::find($request->user['id']);
        $level = StaffGrade::where('id',$user->getData('level'))
            ->field('id,name,img,service_time,money,sort')
            ->findOrEmpty()->toArray();
        $next_level = StaffGrade::where('sort','<',$level['sort'])
            ->field('id,name,img,service_time,money,sort')
            ->order('sort desc')
            ->findOrEmpty()->toArray();
        $res['level'] = $level;
        $res['next_level'] = $next_level;
        $user_server_time = EmployeeInformation::where('staff_people_id',$user['id'])
            ->value('service_time');
        $res['servic_time'] = $user_server_time??0;
        if(!empty($next_level)){
            $curriculum = StudyCourse::where('status',1)
                ->where('pid','<>',0)
                ->where('staff_grade_id',$next_level['id'])
                ->order('pid asc,sort desc')
                ->field('id,name')
                ->withCount('kechen')
                ->select()->toArray();
            $res['curriculum'] = $curriculum;
            //处理技能
            $skill = StaffSkill::where('staff_grade_id',$next_level['id'])
                ->where('status',1)
                ->order('sort desc')
                ->field('id,name')
                ->withCount('jienng')
                ->select()->toArray();
            $res['skill'] = $skill;
        }else{
            $res['curriculum'] = [];
            $res['skill'] = [];
        }
        return api_success('获取成功',$res);
    }

    /**获取视频列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_curriculum_list(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            return api_fail('请传入要查看的类型');
        }
        $data = StudyCourse::where('status',1)
            ->where('pid',$id)
            ->field('id,name,videos,video_href,cover')
            ->select()->toArray();
        return api_success('获取成功',$data);
    }
}